搜索 K
Appearance
博客正在加载中...
Appearance
Java8 新引入了 Instant 类型表示时间戳
Instant now = Instant.now();
System.out.println(now.getEpochSecond()); //秒 1672133167
System.out.println(now.toEpochMilli()); // 毫秒 1672133167386本案例是在 2022 年 12 月 27 日 17:26 分左右运行得到的结果。
个人觉得如果只是为了获取秒数或者毫秒数,使用 System.currentTimeMillis() 来得更为方便
ZonedDateTime Instant 加上一个时区,即可表示一个时间。例如用秒来指定时间戳:
Instant gangang = Instant.ofEpochSecond(1672133167);
ZonedDateTime zdt = gangang.atZone(ZoneId.systemDefault());
System.out.println(zdt); //2022-12-27T17:26:07+08:00[Asia/Shanghai]也可以用毫秒:
Instant g2 = Instant.ofEpochMilli(1672133167386L);
ZonedDateTime zdt2 = g2.atZone(ZoneId.systemDefault());
System.out.println(zdt2);LocalDateTime,ZoneId,Instant,ZonedDateTime 和 long 都可以互相转换:
┌─────────────┐
│LocalDateTime│────┐
└─────────────┘ │ ┌─────────────┐
├───>│ZonedDateTime│
┌─────────────┐ │ └─────────────┘
│ ZoneId │────┘ ▲
└─────────────┘ ┌─────────┴─────────┐
│ │
▼ ▼
┌─────────────┐ ┌─────────────┐
│ Instant │<───>│ long │
└─────────────┘ └─────────────┘上图来自廖雪峰老师画的图:Instant - 廖雪峰的官方网站